package com.bogewang.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bogewang.core.base.BaseApiService;
import com.bogewang.core.base.BaseResponse;
import com.bogewang.core.core.token.TokenUtils;
import com.bogewang.pay.entity.PayCreatePayTokenDTO;
import com.bogewang.pay.entity.PaymentTransactionEntity;
import com.bogewang.pay.mapper.PaymentTransactionMapper;
import com.bogewang.pay.service.PayMentTransacTokenService;
import com.bogewang.twitter.SnowflakeIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PayMentTransacTokenServiceImpl extends BaseApiService<JSONObject> implements
        PayMentTransacTokenService {

    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;

    @Autowired
    private TokenUtils tokenUtils;

    @Override
    public BaseResponse<JSONObject> cratePayToken(PayCreatePayTokenDTO payCreatePayTokenDTO) {
        String orderId = payCreatePayTokenDTO.getOrderId();
        if (StringUtils.isEmpty(orderId)){
            return setResultError("订单号码不能为空！");
        }

        Long payAmount = payCreatePayTokenDTO.getPayAmount();
        if (payAmount == null){
            return setResultError("金额不能为空！");
        }

        Long userId = payCreatePayTokenDTO.getUserId();
        if (userId == null){
            return setResultError("userId不能空");
        }

        //2.将输入插入数据库 待支付记录；
        PaymentTransactionEntity paymentTransactionEntity = new PaymentTransactionEntity();
        paymentTransactionEntity.setOrderId(orderId);
        paymentTransactionEntity.setPayAmount(payAmount);
        paymentTransactionEntity.setUserId(userId);

        //3、生成全局ID
        paymentTransactionEntity.setPaymentId(SnowflakeIdUtils.nextId());
        int result = paymentTransactionMapper.insertPaymentTransaction(paymentTransactionEntity);
        if ( !toDaoResult(result)){
            return setResultError("系统错误！");
        }

        //4.获取主键id
        Long payId = paymentTransactionEntity.getId();
        if (payId == null){
            return setResultError("系统错误！");
        }

        //5.生成支付令牌；
        String keyPrefix = "pay_";
        String token = tokenUtils.createToken(keyPrefix, payId + "");
        JSONObject dataResult = new JSONObject();
        dataResult.put("token", token);

        return setResultSuccess(dataResult);
    }
}
